<?php
/**
 * Created by PhpStorm.
 * User: wugang
 * Date: 2017/11/25
 * Time: 下午6:23
 */

namespace App\Http\Controllers;


use App\Models\Task;
use App\Models\TaskDaily;
use App\Models\TaskMonitor;
use App\Service\UserService;
use Illuminate\Http\Request;

class ParticipateController extends Controller
{

    public function joinTask(Request $request){
        $this->validate($request, [
            'task_id' => 'required|integer'
        ]);
        $task = Task::whereId($request->get('task_id'))->first();
        if($task){
            $user = UserService::authUser();
            if($task->uid == $user->id){
                return self::responseError(1004, '不能参与自己的任务');
            }
            $user_ids = $task->supervisors;
            if($user_ids){
                $user_ids = explode(',',$user_ids);
                $user_ids[] = $user->id;
                $user_ids   = array_unique($user_ids);
                $task->supervisors = implode(',',$user_ids);
            }else{
                $task->supervisors = $user->id;
            }
            $task->update();
        }
        return self::responseSuccess('ok');
    }


    public function notifyJoinerUpdate(Request $request){
        $user = UserService::authUser();
        $notices = \Cache::getRedis()->lrange('user_notification_'.$user->id,0 , -1);
        if($notices){
            $ids = array_map(function($element){ return $element['task_id']; },$notices);
            return self::responseSuccess(Task::whereIn('id',$ids)->get());
        }
        return self::responseSuccess([]);
    }


    public function praiseTask(Request $request){
        $this->validate($request, [
            'task_daily_id' => 'required|integer',
            'completion_state' => 'required|in:1,2',
            'comment' => 'required|string|max:256'
        ]);
        $task_daily = TaskDaily::whereId($request->get('task_daily_id'))->first();
        if($task_daily){
            $user = UserService::authUser();
            $task = $task_daily->task;
            if($task->uid == $user->id){
                return self::responseError(1004, '不能参与自己的任务');
            }
            if(TaskMonitor::whereDailyId($task_daily->id)->whereSupervisorUid($user->id)->count() == 0){
                $monitor = new TaskMonitor();
                $monitor->daily_id = $task_daily->id;
                $monitor->supervisor_uid = $user->id;
                $monitor->completion_state = $request->get('completion_state');
                $monitor->comment = $request->get('comment');
                $monitor->save();
                //计算是否当天已完成
                $users = $task->task_join_users;
                if(TaskMonitor::whereDailyId($task_daily->id)->whereCompletionState(1)->count() >= 0.5 * $users->count()){
                    $task_daily->state = 1;
                    $task_daily->update();
                }
            }
        }
        return self::responseSuccess('ok');
    }

}